﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace FullSearch.Common
{
    public class DocCommmon
    {
        private static readonly object _locker = new object();

        private static readonly Dictionary<RuntimeTypeHandle, string> primaryKeyDict = new Dictionary<RuntimeTypeHandle, string>();

        public static string GetPrimaryKey<T>()
        {
            var t = typeof(T);
            var handler = t.TypeHandle;
            var ok = primaryKeyDict.TryGetValue(handler, out var val);
            if (!ok)
            {
                lock (_locker)
                {
                    if (!primaryKeyDict.ContainsKey(handler))
                    {
                        string key = null;
                        var props = t.GetProperties();
                        foreach (var item in props)
                        {
                            var name = item.Name;
                            if (name.ToLower() == "id")
                            {
                                key = name;
                                break;
                            }
                            else
                            {
                                var keyAttr = item.GetCustomAttribute<DocFieldKeyAttribute>();
                                if (keyAttr != null)
                                {
                                    key = name;
                                    break;
                                }
                                else
                                {
                                    throw new Exception("can not found DocFieldKeyAttribute");
                                }
                            }
                        }
                        primaryKeyDict.Add(handler, key);
                    }
                }
                val = primaryKeyDict[handler];
            }
            return val;
        }
    }
}
